using System;
using System.IO;
using System.Reflection;

namespace Framework.Library.Core.Utils.IO
{
    public class ResourceStreamGetter : IStreamGetter
    {
        private Assembly _resourceAssembly;
        private string _resourceName;

        public Assembly ResourceAssembly
        {
            get { return _resourceAssembly; }
            set { _resourceAssembly = value; }
        }

        public string ResourceName
        {
            get { return _resourceName; }
            set { _resourceName = value; }
        }

        #region IStreamGetter Members

        public Stream GetStream()
        {
            if (string.IsNullOrEmpty(_resourceName))
                throw new InvalidOperationException("ResourceName must be set.");

            // if resource assembly has not been set, default to the currently executing assembly
            Assembly assembly = _resourceAssembly ?? Assembly.GetExecutingAssembly();
            Stream resourceStream = assembly.GetManifestResourceStream(_resourceName);

            if (resourceStream == null)
                throw new Exception(string.Format("Could not find resource '{0}' in assmebly '{1}'.", _resourceName,
                                                  assembly.FullName));

            return resourceStream;
        }

        #endregion
    }
}